package com.qfedu.user.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.qfedu.common.entity.User;
import com.qfedu.common.exception.CommonException;
import com.qfedu.common.utils.JwtUtils;
import com.qfedu.user.mapper.LoginMapper;
import com.qfedu.user.param.LoginParam;
import com.qfedu.user.service.LoginService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * 2025/1/13下午8:46
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private LoginMapper loginMapper;

    /**
     * 登录
     */
    @Override
    public String login(LoginParam loginParam) {

        // 前端传的密码进行MD5运算
        String md5pwd = SecureUtil.md5(loginParam.getPassword());
        loginParam.setPassword(md5pwd);
        User user =loginMapper.login(loginParam);

        if (user == null) {
            throw new CommonException("用户名或密码错误");
        }
        if (!user.getPassword().equals(md5pwd)) {
            throw new CommonException("用户名或密码错误");
        }

        // 生成JWT token
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("username", user.getUsername());
        map.put("avatar",user.getAvatar());

        String token = JwtUtils.createJwt(map);

        return token;
    }
}
